/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webbucks;

import java.sql.*;
import java.util.*;

/**
 *
 * @author Locally
 */
public class ShoppingCartBean {

        final String url = "jdbc:mysql://localhost:8889/";
        final String dbName = "webbucks";
        final String driver = "com.mysql.jdbc.Driver";
        final String user = "root"; 
        final String pw = "root";
    public class CartItem {
        String k;
        ProductBean p;
        Integer n;
        
        public int getN() {
            return n;
        }
        public ProductBean getP() {
            return p;
        }
        public String getK() {
            return k;
        }
    }
    
    Map<String, CartItem> cart = new HashMap<String, CartItem>();
    int total_price=0;
    
    public ShoppingCartBean() {
    }
    
    public void removeProduct() {
    }
    
    public Map<String,CartItem> getCart() {
        return cart;
    }
    
    public int getTotalPrice() {
        return total_price;
    }
    
    public void addProduct(String name) {
        if (cart.containsKey(name)) {
            System.out.println("Hittade varan i Cart");
            cart.get(name).n++;
        } else {
            CartItem ci = new CartItem();           
            System.out.println("Hittade inte varan i Cart");
            ci.n=1;
            ci.k=name;
            ci.p=new ProductBean(name);
            cart.put(ci.k,ci);            
        }
        total_price+=cart.get(name).p.getPrice();       
    }
    
    public void removeProduct(String name) {
        cart.get(name).n--;
        total_price-=cart.get(name).p.getPrice();       
        if (cart.get(name).n==0) {
            cart.get(name).p=null;
            cart.remove(name);
        }
    }
        public Map<String,String> finishOrder(String customer){
        Map<String, String> orderStatus = new HashMap<String, String>();
        Map<String, Integer> orderStatusNumbers = new HashMap<String, Integer>();

        try{
          Class.forName(driver).newInstance();
            Connection con=DriverManager.getConnection(url+dbName,user,pw);
            Connection con2=DriverManager.getConnection(url+dbName,user,pw);
            Statement stmt;
            int count = 0;
            for(Map.Entry<String,CartItem> entry : cart.entrySet()){
                count = 0;
                CartItem c = entry.getValue();
                int numberOfProducts = c.getN();
                ProductBean p = c.getP();
                List<Ingredient> l;
                for(int i = 0; i < numberOfProducts; i++){
                    l = p.getIngredients();
                    boolean success= true;
                    try{
                        
                        con.setAutoCommit(false);
                        Savepoint save1 = con.setSavepoint();
                        
                        
                        

                        for(Ingredient currIng : l){ // pre-check
                            
                            stmt = con.createStatement();
                            String query = "Select supply from ingredients where name=\"" + (currIng.getName()) + "\"";
                            System.out.println(query);
                            ResultSet rs = stmt.executeQuery(query);
                            System.out.println("checking if it worked...");
                            if(rs.next()){
                                System.out.println("checking if to rollback...");
                                if(rs.getInt("supply") < 1){
                                    System.out.println("rollback!");
                                    con.rollback(save1);
                                    success = false;
                                    break;
                                }
                            }
                            stmt.close();
                        }

                       
                        for(Ingredient currIng : l){ // pre-check
                            
                            stmt = con.createStatement();
                            String query = "Select supply from ingredients where name=\"" + (currIng.getName()) + "\"";
                            System.out.println(query);
                            ResultSet rs = stmt.executeQuery(query);
                            System.out.println("checking if it worked...");
                            if(rs.next()){
                                System.out.println("checking if to rollback...");
                                if(rs.getInt("supply") < 1){
                                    System.out.println("rollback!");
                                    con.rollback(save1);
                                    success = false;
                                    break;
                                }
                            }
                            stmt.close();
                        }

                        
                        if(!success){
                            orderStatus.put(p.getName(), ""+i + " of "+ numberOfProducts + " was succesfully ordered, out of stock for remaining order.");               
                            orderStatusNumbers.put(p.getName(),i);               
                            
                            break;
                        }
                        
                        for(Ingredient currIng : l){ //Update ingredients for product p
     
                            //get supply
                            Statement stmt2 = con.createStatement();
                            String supplyQry = "Select supply from ingredients where name=\"" + (currIng.getName()) + "\"";
                            System.out.println(supplyQry);
                            ResultSet rs = stmt2.executeQuery(supplyQry);
                            rs.next();
                            int cs = rs.getInt("supply");
                            stmt2.close();
                            
                            stmt = con.createStatement();
                            
                            if(success){
                                String query = "UPDATE ingredients SET supply="+ (cs-1) + " where name =\"" + currIng.getName() + "\"";
                                System.out.println(query);
                                int rowsMod = stmt.executeUpdate(query);
                                if(rowsMod != 1){
                                    con.rollback(save1);
                                    con.commit();
                                    orderStatus.put(p.getName(), ""+i + " of "+ numberOfProducts + " was succesfully ordered, out of stock for remaining order.");
                                    orderStatusNumbers.put(p.getName(),i);               
                            
                                    i = numberOfProducts;
                                    break;
                                }
                            }
                            stmt.close();
                        }
                        //success = true;
                        for(Ingredient currIng : l){
                            
                            stmt = con2.createStatement();
                            String query = "Select supply from ingredients where name=\"" + (currIng.getName()) + "\"";
                            System.out.println(query);
                            ResultSet rs = stmt.executeQuery(query);
                            System.out.println("checking if it worked...");
                            if(rs.next()){
                                System.out.println("checking if to rollback...");
                                if(rs.getInt("supply") < 0){
                                    System.out.println("rollback!");
                                    con.rollback(save1);
                                    success = false;
                                    break;
                                }
                            }
                            stmt.close();
                        }
                        if(success == true){
                            con.commit();
                            
                            
          
                        }
                        
                        
                    }
                    catch(Exception e){
                        con.rollback();
                        orderStatus.put(p.getName(), ""+i + " of "+ numberOfProducts + " was succesfully ordered, out of stock for remaining order.");               
                        orderStatusNumbers.put(p.getName(),i); 
                        i = numberOfProducts;
                    }
                    
                   if(success == true){
                       count++;
                   }
                   if(i == numberOfProducts-1){
                        orderStatus.put(p.getName(), count +" of "+numberOfProducts +" was succesfully ordered");
                        orderStatusNumbers.put(p.getName(),count); 
                        count = 0;
                   }
                }
                con.commit();
            }
            con.close();
            con2.close();
        }
        catch(Exception e){
            System.out.println("Database could not connect in ShoppingCartBean.java");
            System.out.println("Exception caught: " + e);
            
        }
          updateOrder(customer, orderStatusNumbers);
        //NEW SHOPPING CART 

        
        return orderStatus;
    }
        
        public void updateOrder(String customer, Map<String,Integer> orderStatusNumbers){
    
            try{
                    Class.forName(driver).newInstance();
                    Connection con=DriverManager.getConnection(url+dbName,user,pw);
                    int amount;
                    String fields = "customer,";
                    String values = "\""+customer+"\",";
                    for(Map.Entry<String,Integer> entry : orderStatusNumbers.entrySet()){
                        
                        fields = fields + entry.getKey() +",";
                        values = values + entry.getValue() +",";
                        
                        //String insertQuery = "INSERT INTO orderstatus(customer,"+entry.getKey()+") VALUES(\""+customer+"\","+entry.getValue()+")";
                        
                        
                    }
                    fields = fields.substring(0, fields.length() - 1);
                    values = values.substring(0, values.length() - 1);
                    String insertQuery = "INSERT INTO orderstatus("+fields+ ") VALUES("+values+")";
                    System.out.println(insertQuery);
                    Statement stmt = con.createStatement();
                    int mod = stmt.executeUpdate(insertQuery);
                    stmt.close();
                    if(mod !=1){
                        System.out.println("FATAL ERROR, UPDATING ORDER MODIFIED more/LESS ONE FIELD!");
                    }
                    con.close();
            }       
            catch(Exception e){
                System.out.println("Could not add order for customer, exception: " +e);
            }
        }
}
